<template>
  <div class="app-container">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="出入仓类型" prop="type">
            <el-select v-if="editAble" v-model="form.type" placeholder="出入仓类型" disabled>
              <el-option
                v-for="dict in inout_storehouse"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <dict-tag v-else :options="inout_storehouse" :value="form.type" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出仓单编号" prop="code">
            <code-input
              v-if="editAble"
              v-model="form.code"
              code="OUT_STORE_CODE"
              :disabled="!!form.id"
              placeholder="请输入出仓单编号"
            />
            <el-tooltip v-else effect="dark" :content="form.code">
              <div class="form-text">{{ form.code }}</div>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出仓名单称" prop="name">
            <el-input v-if="editAble" v-model="form.name" placeholder="请输入出仓名单称" />
            <el-tooltip v-else effect="dark" :content="form.name">
              <div class="form-text">{{ form.name }}</div>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <SearchTool
          v-if="editAble"
          :code="{
            factory: 'factoryCode',
            workshop: 'workshopCode',
            line: 'lineCode',
            section: 'sectionCode',
          }"
          :titles="{
            factory: '工厂',
            workshop: '工段',
            line: '产线',
            section: '工艺段',
          }"
          :layout="true"
          :span="6"
          v-model:factory="form.factoryCode"
          v-model:workshop="form.workshopCode"
          v-model:line="form.lineCode"
          v-model:section="form.sectionCode"
          @lineChange="toolChange"
          @sectionChange="toolChange"
        ></SearchTool>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="工厂" prop="factoryCode">
            <div class="form-text">{{ form.factoryName }}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="工段" prop="workshopCode">
            <div class="form-text">{{ form.workShopName }}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="产线" prop="lineCode">
            <div class="form-text">{{ form.lineName }}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!editAble" :span="6">
          <el-form-item label="工艺段" prop="sectionCode">
            <div class="form-text">{{ form.sectionName }}</div>
          </el-form-item>
        </el-col>
        <el-form-item
          v-if="operationTitle == '退料出仓详情' || operationTitle == '确认出仓'"
          label="出仓时间"
          prop="launchTime"
          :rules="
            operationTitle == '确认出仓' && [
              {
                required: true,
                message: '请选择出仓时间',
                trigger: 'blur',
              },
            ]
          "
        >
          <el-date-picker
            v-if="operationTitle == '确认出仓'"
            clearable
            v-model="form.launchTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择出仓时间"
          ></el-date-picker>
          <el-tooltip v-else effect="dark" :content="form.launchTime">
            <div class="form-text">{{ form.launchTime }}</div>
          </el-tooltip>
        </el-form-item>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-if="editAble"
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
            />
            <div v-else class="form-text">{{ form.remark }}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!form.status == 'outed_warehouse'" :span="6">
          <el-form-item label="确认出仓人" prop="launchPerson">
            <div class="form-text">{{ form.launchPerson }}</div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="出仓明细" name="first">
        <el-row v-if="editAble" :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="plus" @click="handleAddWhStorehouseInDetail">
              选择物料
            </el-button>
          </el-col>
        </el-row>
        <el-form ref="tableForm" :model="whStorehouseInDetailList" label-width="0">
          <el-table
            :data="whStorehouseInDetailList"
            :row-class-name="rowWhStorehouseInDetailIndex"
            border
            maxHeight="400"
            cell-class-name="table-form-item"
            ref="whStorehouseInDetail"
          >
            <el-table-column label="序号" align="center" prop="index" width="80" />
            <!-- <el-table-column label="ERP订单编号" prop="ErpCode" width="150">
                <template #default="scope">
                  <el-form-item label="">
                    <el-input
                      v-model="scope.row.orderCode"
                      placeholder="请输入订单"
                    />
                  </el-form-item>
                </template>
              </el-table-column> -->
            <el-table-column label="ERP订单编号" prop="orderCode" width="150"></el-table-column>
            <el-table-column label="产品名称" prop="productName" width="150"></el-table-column>
            <el-table-column label="产品编号" prop="bomCode" width="150"></el-table-column>
            <el-table-column label="物料编号" prop="whCode" width="150"></el-table-column>
            <el-table-column label="物料名称" prop="whName" width="150"></el-table-column>
            <el-table-column label="批次号" prop="batchNo" width="150"></el-table-column>
            <el-table-column label="线边仓" prop="storehouseName" width="150"></el-table-column>
            <el-table-column label="库位" prop="binName" width="150"></el-table-column>
            <el-table-column label="库存" prop="stockNum" width="150"></el-table-column>
            <el-table-column label="数量" prop="deliveryNumber" width="150">
              <template v-if="editAble" #header>
                <span style="color: red">*</span>
                <span>数量</span>
              </template>
              <template v-if="editAble" #default="scope">
                <el-form-item
                  label=""
                  :prop="`[${scope.$index}].deliveryNumber`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入数量',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input-number
                    v-model="scope.row.deliveryNumber"
                    controls-position="right"
                  ></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="unit" width="150"></el-table-column>
            <el-table-column
              v-if="binEditAble"
              label="操作"
              align="center"
              fixed="right"
              minWidth="100"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  icon="delete"
                  type="primary"
                  @click="handleDeleteWhStorehouseInDetail(scope.row, scope.$index)"
                  v-hasPermi="['warehouse:inStorehouse:remove']"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <matDialog
      v-model="show"
      :factory="form.factoryCode"
      :workshop="form.workshopCode"
      :line="form.lineCode"
      :section="form.sectionCode"
      @change="handleChange"
    ></matDialog>
  </div>
</template>

<script setup name="warehouse">
import {
  getWhStorehouseOut,
  addWhStorehouseOut,
  confirmOutStorehouse,
} from "@/api/warehouse/WhStorehouseOut";
import {
  listWhStorehouseOutdetail,
  delWhStorehouseOutdetail,
} from "@/api/warehouse/WhStorehouseOutdetail";
import { reactive, toRefs, useAttrs, ref, getCurrentInstance, onMounted } from "vue";
import matDialog from "@/components/matDialog/matDialog.vue";
import { v4 as uuidv4 } from "uuid";
const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const activeName = ref("first");
const { inout_storehouse } = proxy.useDict("inout_storehouse");
const operationTitle = ref("");
const isBatch = ref(false);
const refData = reactive({
  // 表单参数
  form: {},
  // 表单校验
  rules: {},
});
const { form, rules } = toRefs(refData);
const emit = defineEmits(["close", "setActions", "setIsActionTop"]);
const whStorehouseInDetailList = ref([]);
const formRef = ref("formRef");
const tableForm = ref("tableForm");
const show = ref(false);
const editAble = ref(false);
const binEditAble = ref(false);
const actions = ref([
  {
    text: "取 消",
    theme: "",
    handle: () => {
      cancel();
    },
  },
  {
    text: "确 定",
    theme: "primary",
    handle: () => {
      submitForm();
    },
    loading: false,
  },
]);

// 取消按钮
function cancel() {
  emit("close");
}
// 表单重置
function reset() {
  form.value = {
    id: "",
    type: "2",
    code: "",
    name: "",
    factoryCode: "",
    workshopCode: "",
    lineCode: "",
    sectionCode: "",
    storehouseCode: "",
  };
  formRef.value.resetFields();
  whStorehouseInDetailList.value = [];
}

/** 修改按钮操作 */
function getDetail(id) {
  getWhStorehouseOut(id).then((response) => {
    form.value = response.data;
    if (form.value.launchTime) {
      form.value.launchTime = proxy.parseTime(form.value.launchTime, "{y}-{m}-{d} {h}:{i}:{s}");
    }
    if (operationTitle.value === "确认出仓" && !form.value.launchTime) {
      form.value.launchTime = proxy.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}");
    }
    getListWhStorehouseInDetail(response.data.code);
  });
}

/** 提交按钮 */
function submitForm() {
  if (operationTitle.value == "确认出仓") {
    formRef.value.validate((valid) => {
      if (valid) {
        if (whStorehouseInDetailList.value.length) {
          tableForm.value.validate((result) => {
            if (result) {
              proxy.$modal.confirm("是否提交确认出仓？").then(() => {
                form.value.whStorehouseOutDetail = whStorehouseInDetailList.value;

                addWhStorehouseOut(form.value).then(() => {
                  confirmOutStorehouse(form.value.id).then(() => {
                    proxy.$modal.msgSuccess("提交成功");
                    cancel();
                  });
                });
              });
            }
          });
        } else {
          proxy.$modal.msgError("请添加物料");
        }
      }
    });
  } else {
    formRef.value.validate((valid) => {
      if (valid) {
        if (whStorehouseInDetailList.value.length) {
          tableForm.value.validate((result) => {
            if (result) {
              proxy.$modal.confirm("是否提交出库单？").then(() => {
                form.value.whStorehouseOutDetail = whStorehouseInDetailList.value;

                addWhStorehouseOut(form.value).then(() => {
                  proxy.$modal.msgSuccess("提交成功");
                  cancel();
                });
              });
            }
          });
        } else {
          proxy.$modal.msgError("请添加物料");
        }
      }
    });
  }
}

/** 物料入仓明细序号 */
function rowWhStorehouseInDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}
/** 物料入仓明细添加按钮操作 */
function handleAddWhStorehouseInDetail() {
  formRef.value.validate((valid) => {
    if (valid) {
      show.value = true;
    }
  });
}

function toolChange() {
  whStorehouseInDetailList.value.forEach((el) => {
    el.storehouseCode = "";
    el.binCode = "";
  });
}

function handleChange(val) {
  if (val.length) {
    console.log(val);

    val.forEach((el) => {
      let obj = {};
      obj.randomId = uuidv4();
      obj.orderCode = el.erpOrderNo;
      obj.productName = el.prodName;
      obj.bomCode = el.prodNo;
      obj.whCode = el.matCode;
      obj.whName = el.matName;
      obj.factory = "";
      obj.batchNo = el.batchNo;
      obj.packing = el.packing;
      obj.measureUnit = el.measureUnit;
      obj.unit = el.packageUnit;
      obj.spec = el.packing;
      obj.stockNum = el.num;
      obj.deliveryNumber = 0;
      obj.storehouseCode = el.storehouseCode;
      obj.binCode = el.binCode;
      obj.storehouseName = el.storehouseName;
      obj.binName = el.binName;
      obj.outStoreCode = form.value.code;
      obj.remark = "";
      whStorehouseInDetailList.value.push(obj);
    });
  }
}

/** 物料入仓明细删除按钮操作 */
function handleDeleteWhStorehouseInDetail(row, index) {
  proxy.$modal
    .confirm("是否确认移除序号为 " + (index + 1) + " 的数据项？")
    .then(() => {
      if (row.id) {
        delWhStorehouseOutdetail(row.id).then(() => {
          whStorehouseInDetailList.value = whStorehouseInDetailList.value.filter((item) => {
            return item.id !== row.id;
          });

          proxy.$modal.msgSuccess("移除成功");
        });
      } else {
        whStorehouseInDetailList.value.splice(index, 1);
        proxy.$modal.msgSuccess("移除成功");
      }
    })
    .catch(() => {});
}

function getListWhStorehouseInDetail(code) {
  listWhStorehouseOutdetail({ pageSize: 10000, pageNum: 1, outStoreCode: code }).then((res) => {
    if (isBatch.value) {
      whStorehouseInDetailList.value.push(...res.rows);
    } else {
      whStorehouseInDetailList.value = res.rows;
    }
  });
}

onMounted(() => {
  reset();
  const { data, title, code } = attrs;
  binEditAble.value = true;
  operationTitle.value = title;
  console.log(data);
  editAble.value = false;
  binEditAble.value = false;
  actions.value = [];
  emit("setActions", actions.value);
  if (code) {
    isBatch.value = true;
    const orderCodes = [];
    const names = [];
    const launchPersons = [];
    data.forEach((el) => {
      orderCodes.push(el.code);
      names.push(el.name);
      launchPersons.push(el.launchPerson);
      getListWhStorehouseInDetail(el.code);
    });

    form.value = data[0];
    form.value.id = code.join(",");
    form.value.code = orderCodes.join(",");
    // form.value.erpOrderCode = erpOrderCodes.join(",");
    form.value.name = names.join(",");
  } else {
    isBatch.value = false;
    if (data) {
      getDetail(data.id);
    }
  }
});
</script>

<style lang="scss">
.form-text {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
